package com.shxc.smarttrade.old.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;
import android.widget.Toast;

import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.myview.CustomDialog;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class WebViewActivity extends BaseActivity {

    private static String TAG = WebViewActivity.class.getSimpleName();
    @BindView(R.id.tv_center)
    TextView tvCenter;
    private WebView webview;
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_ALBUM = 100;
    private static final int REQUEST_CAMERA = 101;
    private final static int FILECHOOSER_RESULTCODE = 2;
    private Uri cameraUri;
    private CustomDialog menuDialog;
    private ProgressDialog longDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        initView();
    }

    private void initView() {
        initDialogs();
        longDialog.show();
        webview = (WebView) findViewById(R.id.webview);
        Intent intent = getIntent();
        String url = intent.getStringExtra("url");
        tvCenter.setText("交易开户");

        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webview.clearCache(true);

        webview.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    // 网页加载完成
                    longDialog.dismiss();
                }

            }

            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
//                getImageFromAlbum();
                showMenuDialog();
            }


            // For Lollipop 5.0+ Devices
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;
                showMenuDialog();
                return true;
            }

            //For Android 4.1 only
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;

                showMenuDialog();
//                getImageFromAlbum();
            }

            protected void openFileChooser(ValueCallback<Uri> uploadMsg) {

                mUploadMessage = uploadMsg;
                showMenuDialog();
//                getImageFromAlbum();
            }

        });

        webview.loadUrl(url);
    }

    /**
     * 初始化dialog
     */
    private void initMenuDialog() {
        menuDialog = new CustomDialog(this, R.style.customDialogStyle);
        menuDialog.setCanceledOnTouchOutside(true);
        //监听dialog 取消状态，并设置ValueCallback 为null以及onReceiveValue传递null,否则点击不会有回调
        menuDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                    mUploadMessage = null;
                }
            }
        });
        menuDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                Log.e(TAG, "onDismiss: " + "on dismiss");
            }
        });
        menuDialog.setTakePhotoRunnable(new Runnable() {
            @Override
            public void run() {
                WebViewActivityPermissionsDispatchers.getImgFromCameraWithCheck(WebViewActivity.this);
            }
        });
        menuDialog.setTakePictureRunnable(new Runnable() {
            @Override
            public void run() {
                WebViewActivityPermissionsDispatchers.getImgFromAlbumWithCheck(WebViewActivity.this);
            }
        });
    }

    /**
     * 显示dialog
     */
    private void showMenuDialog() {
        if (menuDialog == null) {
            initMenuDialog();
        }
        menuDialog.show();
    }

    /**
     * 从相册中获取图片
     */
    private void getImageFromAlbum() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), REQUEST_ALBUM);
    }

    /**
     * 拍照获取图片
     */
    private void getImageFromCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File externalDataDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM);
        File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
                File.separator + "browser-photos");
        cameraDataDir.mkdirs();
        String mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
                System.currentTimeMillis() + ".jpg";
        cameraUri = Uri.fromFile(new File(mCameraFilePath));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (requestCode == REQUEST_ALBUM) {
                if (uploadMessage == null)
                    return;
                Uri mGalleryUri = intent.getData();
                //部分手机返回路径存在问题
                if (mGalleryUri.getPath().contains("/external/images/media/")) {
                    String realPathFromUri = "file://" + getRealPathFromUri(this, mGalleryUri);
                    mGalleryUri = Uri.parse(realPathFromUri);
                }
                Log.e("mGalleryUri", mGalleryUri.toString() + "");
                uploadMessage.onReceiveValue(new Uri[]{mGalleryUri});
                uploadMessage = null;
            } else if (requestCode == REQUEST_CAMERA) {
                if (uploadMessage == null)
                    return;
                //部分手机intent返回null
                if (cameraUri != null) {
                    uploadMessage.onReceiveValue(new Uri[]{cameraUri});
                    cameraUri = null;
                }
                uploadMessage = null;

            }
        } else if (requestCode == REQUEST_ALBUM) {
            if (null == mUploadMessage)
                return;
            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
            // Use RESULT_OK only if you're implementing WebView inside an Activity
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else if (requestCode == REQUEST_CAMERA) {
            if (null == mUploadMessage)
                return;
            // Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
            // Use RESULT_OK only if you're implementing WebView inside an Activity
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else
            Toast.makeText(getBaseContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
    }

    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }


    /**
     * 适配6.0后的权限***********************************************************
     */

    /**
     * 拍照 访问相机和读写sd卡
     */
    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void getImgFromCamera() {
        getImageFromCamera();
    }


    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationale(PermissionRequest request) {
        showRationaleDialog("拍照需要访问相机和sd卡的权限，不开启将无法正常工作", request);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDenied() {
        Toast.makeText(this, "没有权限将无法正常使用", Toast.LENGTH_LONG).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAsk() {
        new AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle("权限申请")
                .setMessage("您已禁止不再询问，请前往设置-应用-当前应用权限中开启相机权限，以正常使用拍照")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //开启设置页
                        startActivity(new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS));
                        dialog.dismiss();
                    }
                })
                .show();
    }

    /**
     * 从相册获取照片，需要访问sd卡
     */
    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void getImgFromAlbum() {
        getImageFromAlbum();
    }

    @OnShowRationale({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void noSdCardPermission(PermissionRequest request) {
        showRationaleDialog("需要访问sd卡的权限，不开启将无法正常工作", request);
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showStorageDenied() {
        Toast.makeText(this, "没有权限将无法正常使用", Toast.LENGTH_LONG).show();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        WebViewActivityPermissionsDispatchers.onRequestPermissionsResult(this, requestCode, grantResults);

    }

    private void showRationaleDialog(String messageResId, final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage(messageResId)
                .show();
    }

    @OnClick(R.id.rl_left)
    public void onViewClicked() {
        if (webview.canGoBack()) {
            webview.goBack();
        } else
            finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            webview.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化用于加载的dialog
     */
    private void initDialogs() {
        longDialog = new ProgressDialog(this);
        longDialog.setMessage("开户连接中,预计10～20秒");
        longDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        longDialog.setCancelable(false);
        longDialog.setIndeterminate(false);
    }
}
